package com.news.sentiment.controller;

import com.news.sentiment.annotation.CheckToken;
import com.news.sentiment.enums.ResultEnum;
import com.news.sentiment.pojo.User;
import com.news.sentiment.service.UserService;
import com.news.sentiment.util.JwtUtil;
import com.news.sentiment.vo.Result;
import com.news.sentiment.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/exist")
    public Result isExist(String username){
        UserVo userVo = new UserVo();
        userVo.setUsername(username);
        User user = userService.findByUsernameAndPwd(userVo);

        if(user == null){
           return Result.success(userVo);
        }
        return Result.fail(ResultEnum.USER_IS_EXIST);
    }

    @RequestMapping("/login")
    public Result login(UserVo userVo){
        User user = userService.findByUsernameAndPwd(userVo);
        if(user == null){
            return Result.fail(ResultEnum.USERNAME_OR_PWD_ERROR);
        }
        /* 添加jwt */
        String jwtToken= JwtUtil.createJWT(7 * 24 * 60 * 60 * 1000, user);
        Map<String,String> jsonMap = new HashMap<String,String>();
        jsonMap.put("token",jwtToken);
        return Result.success(jsonMap);
    }


    @RequestMapping("/profile")
    @CheckToken
    public Result updateProfile(UserVo userVo){
        Integer rows  = userService.updateProfile(userVo);
        return Result.success(rows);
    }
}
